package com.example.administrator.accessabilityservicestudy;


import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.luck.picture.lib.entity.LocalMedia;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AutoSendServiece extends AccessibilityService {
    private final static String MM_PNAME = "com.tencent.mm";
    boolean hasAction = false;
    boolean locked = false;
    boolean background = false;
    private String name;
    private String scontent;
    AccessibilityNodeInfo itemNodeinfo;
    private KeyguardManager.KeyguardLock kl;
    private Handler handler = new Handler();

    public static Map<String, String> content_file_map = new HashMap<>();
    public static List<LocalMedia> LIST_FILE = new ArrayList<>();
    public static String CONTENT = "";
    public static boolean ACTIVE = false;
    public static boolean FirstCheck = true;
    public static boolean IS_FILE = false;
    private boolean isSend = false;
    public static String  folderName = "";
    /**
     * 必须重写的方法，响应各种事件。
     *
     * @param event
     */
    @Override
    public void onAccessibilityEvent(final AccessibilityEvent event) {
        int eventType = event.getEventType();
        android.util.Log.d("maptrix", "get event = " + eventType);
        switch (eventType) {
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:// 通知栏事件
                android.util.Log.d("maptrix", "get notification event");
           /*     List<CharSequence> texts = event.getText();
                if (!texts.isEmpty()) {
                    for (CharSequence text : texts) {
                        String content = text.toString();
                        if (!TextUtils.isEmpty(content)) {
                            if (isScreenLocked()) {
                                locked = true;
                                wakeAndUnlock();
                                android.util.Log.d("maptrix", "the screen is locked");
                                if (isAppForeground(MM_PNAME)) {
                                    background = false;
                                    android.util.Log.d("maptrix", "is mm in foreground");
                                    sendNotifacationReply(event);
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            sendNotifacationReply(event);
                                            if (fill()) {
                                                send();
                                            }
                                        }
                                    }, 1000);
                                } else {
                                    background = true;
                                    android.util.Log.d("maptrix", "is mm in background");
                                    sendNotifacationReply(event);
                                }
                            } else {
                                locked = false;
                                android.util.Log.d("maptrix", "the screen is unlocked");
                                // 监听到微信红包的notification，打开通知
                                if (isAppForeground(MM_PNAME)) {
                                    background = false;
                                    android.util.Log.d("maptrix", "is mm in foreground");
                                    sendNotifacationReply(event);
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (fill()) {
                                                send();
                                            }
                                        }
                                    }, 1000);
                                } else {
                                    background = true;
                                    android.util.Log.d("maptrix", "is mm in background");
                                    sendNotifacationReply(event);
                                }
                            }
                        }
                    }
                }*/
                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                android.util.Log.d("maptrix", "get type window down event");
//                if (!hasAction) break;
                itemNodeinfo = null;
                String className = event.getClassName().toString();
                if (className.equals("com.tencent.mm.ui.LauncherUI")) {
                 /*   if (fill()) {
                        send();
                    } else {
                        if (itemNodeinfo != null) {
                            itemNodeinfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (fill()) {
//                                        send();
                                    }
                                    back2Home();
                                    release();
                                    hasAction = false;
                                }
                            }, 1000);
                            break;
                        }
                    }*/
                } else if (className.equals("com.tencent.mm.plugin.sns.ui.En_c4f742e5")) {//文本消息时候的界面
                    handlTextemessage(event);

                } else if (className.equals("com.tencent.mm.plugin.sns.ui.En_424b8e16") && ACTIVE) {//朋友圈界面
                    handleClickEvent(event);

                }else if (className.equals("com.tencent.mm.plugin.sns.ui.En_424b8e16") && !ACTIVE&&isSend) {//朋友圈界面但是发送完成后再次回到朋友圈界面，需要回到主桌面去
                   /* handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isSend = false;
                            back2Home();

                        }
                    },3000);*/


                } else if (className.equals("com.tencent.mm.ui.base.l")) {//朋友圈界面  点击拍照图片的界面
                    handleDialogClickEvent(event);

                } else if (className.equals("com.tencent.mm.ui.base.q") && FirstCheck) {
                    FirstCheck = false;
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            handlePopupWindowEvent();
                        }
                    },1000);


                }

                //bring2Front();
//                back2Home();
//                release();
//                hasAction = false;
                break;
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
                android.util.Log.d("maptrix", "get type content down event");
                String s = "内容发生了变化";
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void handlePopupWindowEvent() {
        //打开相册
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cmi");
            if (list != null && list.size() > 0) {
                for (AccessibilityNodeInfo n : list) {
                    if (n.getClassName().equals("android.widget.LinearLayout") && n.isEnabled()) {
                        n.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    }
                }

            }

            //选择图片界面，打开指定文件夹来获取
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AccessibilityNodeInfo nodeInfoFolder = getRootInActiveWindow();
                    List<AccessibilityNodeInfo> list2 = nodeInfoFolder.findAccessibilityNodeInfosByText(folderName);
                    if (list2 != null && list2.size() > 0) {
                        for (AccessibilityNodeInfo n : list2) {
                            if (n.getClassName().equals("android.widget.TextView") && n.isEnabled()) {
                                AccessibilityNodeInfo m = n.getParent();//对应listview 的item
                                if (m.getClassName().equals("android.widget.LinearLayout") && m.isClickable()) {
                                    m.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                                    ;
                                }
                            }
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        check_send();
                    }
                }
            }, 300);
          /*  handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    check_send();
                }
            }, 1000);*/


        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void check_send() {
        //将指定文件夹下的所有图片都选上
        AccessibilityNodeInfo nodeInfoCheck = getRootInActiveWindow();
        List<AccessibilityNodeInfo> listGridView = nodeInfoCheck.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cmf");
        if (listGridView != null && listGridView.size() > 0) {
            for (AccessibilityNodeInfo n : listGridView) {
                if (n.getClassName().equals("android.widget.GridView") && n.isEnabled()) {
                    for (int i = 0; i < n.getChildCount(); i++) {
                        AccessibilityNodeInfo info = n.getChild(i);
                        AccessibilityNodeInfo checkBox = info.getChild(info.getChildCount() - 2);//gridview的item布局
                        if (checkBox.getClassName().equals("android.view.View")) {

//                            checkBox.performAction(AccessibilityNodeInfo.ACTION_SELECT);
                            checkBox.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
                    }
                }
            }
        }
        List<AccessibilityNodeInfo> wancheng = nodeInfoCheck.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/gy");//完成按钮
        if (wancheng != null && wancheng.size() > 0) {
            for (AccessibilityNodeInfo accessibilityNodeInfo : wancheng) {
                if (accessibilityNodeInfo.getClassName().equals("android.widget.TextView") && accessibilityNodeInfo.isEnabled() && accessibilityNodeInfo.isClickable()) {
                    accessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }
        }


    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void handleDialogClickEvent(AccessibilityEvent event) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> list = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.tencent.mm:id/are");
            if (list != null && list.size() > 0) {
                for (AccessibilityNodeInfo n : list) {
                    if (n.getClassName().equals("android.widget.ListView") && n.isEnabled()) {
                        AccessibilityNodeInfo m = n.getChild(1);//从相册获取
                        AccessibilityNodeInfo p = n.getChild(0);//照片或者视频
                        if (m.getClassName().equals("android.widget.LinearLayout") && m.isClickable()) {
                            m.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
//                       n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

            }
        }
    }

    private void handlTextemessage(AccessibilityEvent event) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (IS_FILE) {//是文件
                    if(!TextUtils.isEmpty(CONTENT)){
                        fill();
                    }
                    send();
                } else {//是文本
                    if (fill()) {
                        send();
                    }
                }

            }
        }, 50);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void handleClickEvent(AccessibilityEvent event) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> list = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.tencent.mm:id/gh");
            if (list != null && list.size() > 0) {
                for (AccessibilityNodeInfo n : list) {
                    if (n.getClassName().equals("android.view.View") && n.isEnabled()) {
                        AccessibilityNodeInfo m = n.getChild(1);
                        AccessibilityNodeInfo p = n.getChild(0);
                        if (m.getClassName().equals("android.widget.RelativeLayout") && m.isClickable()) {
                            if (IS_FILE) {//文件是单击
                                m.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            } else {//文字是长按
                                m.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                            }

                            ACTIVE = false;
                        }
//                       n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

            } else {
                List<AccessibilityNodeInfo> liste = nodeInfo
                        .findAccessibilityNodeInfosByText("Send");
                if (liste != null && liste.size() > 0) {
                    for (AccessibilityNodeInfo n : liste) {
                        if (n.getClassName().equals("android.widget.Button") && n.isEnabled()) {
                            n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
                    }
                }
            }
        }


    }


    /**
     * 寻找窗体中的“发送”按钮，并且点击。
     */
    @SuppressLint("NewApi")
    private void send() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> list = nodeInfo
                    .findAccessibilityNodeInfosByText("发送");
            if (list != null && list.size() > 0) {
                for (AccessibilityNodeInfo n : list) {
                    if (n.getClassName().equals("android.widget.TextView") && n.isEnabled()) {
                        n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

            } else {
                List<AccessibilityNodeInfo> liste = nodeInfo
                        .findAccessibilityNodeInfosByText("Send");
                if (liste != null && liste.size() > 0) {
                    for (AccessibilityNodeInfo n : liste) {
                        if (n.getClassName().equals("android.widget.Button") && n.isEnabled()) {
                            n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
                    }
                }
            }
        }
//        pressBackButton();
        back2Home();
    }


    /**
     * 模拟back按键
     */
    private void pressBackButton() {
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param event
     */
    private void sendNotifacationReply(AccessibilityEvent event) {
        hasAction = true;
        if (event.getParcelableData() != null
                && event.getParcelableData() instanceof Notification) {
            Notification notification = (Notification) event
                    .getParcelableData();
            String content = notification.tickerText.toString();
            String[] cc = content.split(":");
            name = cc[0].trim();
            scontent = cc[1].trim();

            android.util.Log.i("maptrix", "sender name =" + name);
            android.util.Log.i("maptrix", "sender content =" + scontent);


            PendingIntent pendingIntent = notification.contentIntent;
            try {
                pendingIntent.send();
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressLint("NewApi")
    private boolean fill() {
        String content = "";
        String file_path;
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode != null) {
           /* if (content_file_map != null && content_file_map.size() > 0) {
                Iterator iterator = content_file_map.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    content = (String) entry.getKey();
                    file_path = (String) entry.getValue();
                }
            }*/
            if (TextUtils.isEmpty(CONTENT)) {
                return false;
            }
            return findEditText(rootNode, CONTENT);
        }
        return false;
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private boolean findEditText(AccessibilityNodeInfo rootNode, String content) {
        int count = rootNode.getChildCount();

        android.util.Log.d("maptrix", "root class=" + rootNode.getClassName() + "," + rootNode.getText() + "," + count);
        for (int i = 0; i < count; i++) {
            AccessibilityNodeInfo nodeInfo = rootNode.getChild(i);
            if (nodeInfo == null) {
                android.util.Log.d("maptrix", "nodeinfo = null");
                continue;
            }

            android.util.Log.d("maptrix", "class=" + nodeInfo.getClassName());
            android.util.Log.e("maptrix", "ds=" + nodeInfo.getContentDescription());
            if (nodeInfo.getContentDescription() != null) {
                int nindex = nodeInfo.getContentDescription().toString().indexOf(name);
                int cindex = nodeInfo.getContentDescription().toString().indexOf(scontent);
                android.util.Log.e("maptrix", "nindex=" + nindex + " cindex=" + cindex);
                if (nindex != -1) {
                    itemNodeinfo = nodeInfo;
                    android.util.Log.i("maptrix", "find node info");
                }
            }
            if ("android.widget.EditText".equals(nodeInfo.getClassName())) {
                android.util.Log.i("maptrix", "==================");
                Bundle arguments = new Bundle();
                arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,
                        AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD);
                arguments.putBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN,
                        true);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
                        arguments);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                ClipData clip = ClipData.newPlainText("label", content);
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setPrimaryClip(clip);
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                return true;
            }

            if (findEditText(nodeInfo, content)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void onInterrupt() {

    }

    /**
     * 判断指定的应用是否在前台运行
     *
     * @param packageName
     * @return
     */
    private boolean isAppForeground(String packageName) {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(packageName)) {
            return true;
        }

        return false;
    }


    /**
     * 将当前应用运行到前台
     */
    private void bring2Front() {
        ActivityManager activtyManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activtyManager.getRunningTasks(3);
        for (ActivityManager.RunningTaskInfo runningTaskInfo : runningTaskInfos) {
            if (this.getPackageName().equals(runningTaskInfo.topActivity.getPackageName())) {
                activtyManager.moveTaskToFront(runningTaskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
                return;
            }
        }
    }

    /**
     * 回到系统桌面
     */
    private void back2Home() {
        Intent home = new Intent(Intent.ACTION_MAIN);

        home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        home.addCategory(Intent.CATEGORY_HOME);

        startActivity(home);
    }



    /**
     * 系统是否在锁屏状态
     *
     * @return
     */
    private boolean isScreenLocked() {
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        return keyguardManager.inKeyguardRestrictedInputMode();
    }

    private void wakeAndUnlock() {
        //获取电源管理器对象
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

        //获取PowerManager.WakeLock对象，后面的参数|表示同时传入两个值，最后的是调试用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");

        //点亮屏幕
        wl.acquire(1000);

        //得到键盘锁管理器对象
        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        kl = km.newKeyguardLock("unLock");

        //解锁
        kl.disableKeyguard();

    }

    private void release() {

        if (locked && kl != null) {
            android.util.Log.d("maptrix", "release the lock");
            //得到键盘锁管理器对象
            kl.reenableKeyguard();
            locked = false;
        }
    }


}


